<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Bill\Controllers;


use App\Eloquent\Ygt\BillLog;
use App\Eloquent\Ygt\Company;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\WarehouseBill;
use App\Eloquent\Ygt\SellerBill;
use App\Engine\Func;
use Framework\BaseClass\Api\Controller;

class IndexController extends Controller
{
    public $userId          = 25;
    public function index()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        if( !$userInfo )
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = ['id'=>$companyId];
        $fields             = 'fixed_money,income_money,pay_money,money_in,money_out,money_use';
        $info               = Company::getInfo($where,$fields);
        $moneyInMonth       = $moneyOutMonth = 0;
        if(!$info)
        {
            xThrow( ERR_UNKNOWN );
        }
        $result             = $info->toArray();
        $nowTime            = $_SERVER['REQUEST_TIME'];
        $nowYm              = date('Y-m',$nowTime);
        $startTime          = $nowYm.'-1';
        $startTimeInt       = strtotime($startTime);
//        $moneyInMonth       = BillLog::where('type','=',2)->where('created_at','>',$startTimeInt)->sum('money');
//        $moneyOutMonth      = BillLog::where('type','=',1)->where('created_at','>',$startTimeInt)->sum('money');
        $moneyInMonth       = BillLog::where('company_id','=',$companyId)->whereIn('type',[2,4])->where('created_at','>',$startTimeInt)->sum('money');
        $moneyOutMonth      = BillLog::where('company_id','=',$companyId)->whereIn('type',[1,3])->where('created_at','>',$startTimeInt)->sum('money');

        //最近一笔改为当日最大一笔 zhuyujun 20180928
        $curDayTime = strtotime(date('Ymd'));

        $moneyIn = '0.00';
        $where              = ['type'=>2];
//        $curDayMaxIn = BillLog::where($where)->where('created_at','>',$curDayTime)->max('money');
        $curDayMaxIn = BillLog::whereIn('type',[2,4])->where('created_at','>',$curDayTime)->max('money');
        if($curDayMaxIn){
            $moneyIn = $curDayMaxIn;
        }

        $moneyOut = '0.00';
        $where              = ['type'=>1];
//        $curDayMaxOut = BillLog::where($where)->where('created_at','>',$curDayTime)->max('money');
        $curDayMaxOut = BillLog::whereIn('type',[1,3])->where('created_at','>',$curDayTime)->max('money');
        if($curDayMaxIn){
            $moneyOut = $curDayMaxOut;
        }

        //获得应收款
        $where              = ['company_id'=>$companyId,'status'=>0];
        $result['income_money']         = WarehouseBill::where($where)->sum('now_money');
        //获得应付款
        $where              = [
            'company_id'=>$companyId,
            'status'=>0
        ];
        $result['pay_money']         = SellerBill::where($where)->sum('now_money');

        $result['money_in_month']   = $moneyInMonth;//本月收入
        $result['money_out_month']  = $moneyOutMonth;//本月支出
        $result['money_in']   = $moneyIn;//已收入
        $result['money_out']   = $moneyOut;//已支出
        return $result;
    }
    public function setMoney()
    {
        $userId             = Func::getHeaderValueByName('userid',$this->userId);
        $userInfo           = DepartmentUser::getCurrentInfo($userId);
        $money              = request('money',0);
        if( !$userInfo || !$money)
        {
            xThrow( ERR_PARAMETER );
        }
        $companyId          = $userInfo->company_id;
        $where              = ['id'=>$companyId];
        $data               = ['fixed_money'=>$money];
        $result             = Company::updateOneData($where,$data);
        if($result === false)
        {
            xThrow(ERR_UNKNOWN);
        }
        return ['messsage'=>'修改成功'];
    }

    //销售员确认发货
    public function sellerComfirmSend(){
        $warehouseSendId = request('warehouse_send_id');

        $tmpWarehouseSendRow = \App\Eloquent\Ygt\WarehouseSend::where(['id'=>$warehouseSendId])->first();
        $companyId = $tmpWarehouseSendRow['company_id'];

        //获取登陆用户信息
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        if($tmpWarehouseSendRow['status'] != 1){
            return [
                'code' => 1,
                'message' => '已确认发货，请刷新界面'
            ];
        }

        $customerOrderId = 0;//获取个订单ID用于发送消息

        //获取到关联的交货单列表
        $outRelationIdArr = \App\Eloquent\Ygt\WarehouseSendRelation::where(['warehouse_send_id'=>$warehouseSendId])->get()->pluck('out_relation_id');
        $warehouseBillIdArr = \App\Eloquent\Ygt\WarehouseOutRelation::whereIn('id',$outRelationIdArr)->get()->pluck('warehouse_bill_id');
        $warehouseBillList= \App\Eloquent\Ygt\WarehouseBill::whereIn('id',$warehouseBillIdArr)->get();

        foreach ($warehouseBillList as $warehouseBillRow){
            //修改状态为销售员确认发货
            $warehouseBillRow->status = 4;
            $warehouseBillRow->save();

            //自动生成应收单
            $tmpObj = \App\Eloquent\Ygt\WarehouseBillMoney::firstOrNew(['warehouse_bill_id'=>$warehouseBillRow['id']]);//防止重复生成
            $tmpInsertRow = $warehouseBillRow->toArray();
            //数据调整
            unset($tmpInsertRow['id']);
            unset($tmpInsertRow['created_at']);
            unset($tmpInsertRow['updated_at']);
            $tmpInsertRow['warehouse_bill_id'] = $warehouseBillRow['id'];
            $tmpInsertRow['status'] = 1;//未收款
            $tmpInsertRow['sn']  = \App\Engine\Sn::createWarehouseBillMoneySn();
            $tmpObj->fill($tmpInsertRow);
            $tmpObj->save();

            //修改发货单状态
            $tmpWarehouseSendRow->status = 2;//已发货
            $tmpWarehouseSendRow->save();

            //获取个订单ID用于发送消息
            if(!$customerOrderId){
                $tmpWarehouseBillId = $warehouseBillRow['id'];//交货单ID
                $tmpWarehouseBillRelation = \App\Eloquent\Ygt\WarehouseBillRelation::where(['warehouse_bill_id'=>$tmpWarehouseBillId])->first();
                $tmpOrderId = $tmpWarehouseBillRelation['order_id'];
                $customerOrderId = \App\Eloquent\Ygt\Order::where(['id'=>$tmpOrderId])->first()->customer_order_id;
            }

        }


        //发送消息给客户
        $foreignKey = $customerOrderId;

        $customerUid = '';
        $customerId = \App\Eloquent\Ygt\CustomerOrder::where(['id'=>$customerOrderId])->first()->customer_name;
        $customerRow = \App\Eloquent\Ygt\Customer::where(['id'=>$customerId])->first();

        if($customerRow){
            $customerUid = $customerRow['user_id'];
            $data = [
                'company_id' => 2,
                'privilege_id' => '',
                'form_user_id' => $userId,
                'to_user_id' => $customerUid,
                'foreign_key' => $foreignKey,
                'type' => 43,//发货单详情
                'type_id' => $warehouseSendId,
                'title' => '订单已确认发货',
                'content' => '订单已确认发货',
                'theme' => '订单已确认发货',
            ];
            \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
        }

        return '操作成功';
    }

    //发货单详情
    public function getWarehouseSendDetail(){
        $warehouseSendId = request('warehouse_send_id');
        $isReplaceCustomer = request('is_replace_customer');//是否代替客户收货

        //获取登陆用户信息
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        //发货单详情
        $tmpWarehouseSendRow = \App\Eloquent\Ygt\WarehouseSend::where(['id'=>$warehouseSendId])->first();
        $companyId = $tmpWarehouseSendRow['company_id'];

        //物流信息
        $tmpLogisticsNotesRow = \App\Eloquent\Ygt\LogisticsNotes::where(['warehouse_send_id'=>$warehouseSendId])->first();

        //发货单关联的成品详情
        $tmpWarehouseSendRelationList = \App\Eloquent\Ygt\WarehouseSendRelation::where(['warehouse_send_id'=>$warehouseSendId])->get();

        /**数据整理**/
        //专线
        $logisticsLine = '';
        if($tmpLogisticsNotesRow){
            $tmpLogisticsLine =  \App\Eloquent\Ygt\LogisticsLine::where(['id'=>$tmpLogisticsNotesRow['line_id']])->first();
            if($tmpLogisticsLine){
                $logisticsLine =  $tmpLogisticsLine['title'];
            }
        }
        //物流公司
        $logistics = '';
        if($tmpLogisticsNotesRow){
            $tmpLogistics =  \App\Eloquent\Ygt\Logistics::where(['id'=>$tmpLogisticsNotesRow['logistics_id']])->first();
            if($tmpLogistics){
                $logistics =  $tmpLogistics['title'];
            }
        }

        //行驶证&驾驶证
        $drivingLicenseImg = $driverLicenseImg = '';
        if($tmpLogisticsNotesRow){
            $drivingLicenseId = $tmpLogisticsNotesRow['driving_license'];
            $driverLicenseId = $tmpLogisticsNotesRow['driver_license'];
            $drivingLicenseImg = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($drivingLicenseId);
            $driverLicenseImg = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($driverLicenseId);
        }

        //附件图
        $otherImgList = [];
        if($tmpLogisticsNotesRow){
            $otherImgIdsStr = $tmpLogisticsNotesRow['img_ids'];
            $otherImgIdsArr = explode(',',$otherImgIdsStr);
            foreach ($otherImgIdsArr as $otherImgId){
                if($otherImgId){
                    $tmpImgUrl = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($otherImgId);
                    $otherImgList[] = $tmpImgUrl;
                }
            }
        }

        //发货时间
        $sendTime = '';
        if($tmpLogisticsNotesRow){
            $tmpTimeArr = $tmpLogisticsNotesRow->toArray();
            $sendTime = date('Y-m-d',$tmpTimeArr['created_at']);
        }

        //成品信息
        $finishProductList = [];
        $customerId = '';//获取发货单相关的客户ID
        foreach ($tmpWarehouseSendRelationList as $tmpWarehouseSendRelationRow){
            //按交货单分组，获取对应的交货单
            $tmpWarehouseOutRelationId = $tmpWarehouseSendRelationRow['out_relation_id'];
            $tmpWarehouseOutRelationRow = \App\Eloquent\Ygt\WarehouseOutRelation::where(['id'=>$tmpWarehouseOutRelationId])->first();

            if(!$customerId && $tmpWarehouseOutRelationRow){
                $customerId = $tmpWarehouseOutRelationRow['customer_id'];
            }

            $tmpWarehouseBillId = $tmpWarehouseOutRelationRow['warehouse_bill_id'];
            if(!isset($finishProductList[$tmpWarehouseBillId])){
                $tmpWarehouseBillRow = \App\Eloquent\Ygt\WarehouseBill::where(['id'=>$tmpWarehouseBillId])->first();
                $finishProductList[$tmpWarehouseBillId] = [
                    'warehouse_bill_id' => $tmpWarehouseBillId,
                    'warehouse_bill_sn' => $tmpWarehouseBillRow['sn'],
                    'list' => [],
                ];
            }


            $finishProductRow = [];
            //获取对应的成品信息
            $tmpWarehouseId = $tmpWarehouseSendRelationRow['warehouse_id'];
            $tmpWarehouseRow = \App\Eloquent\Ygt\Warehouse::where(['id'=>$tmpWarehouseId])->first();
            $finishProductRow['number'] = $tmpWarehouseSendRelationRow['number'];//数量
            $finishProductRow['price'] = $tmpWarehouseSendRelationRow['price'];//单价
            $finishProductRow['money'] = $tmpWarehouseSendRelationRow['money'];//总价
            $finishProductRow['packages'] = $tmpWarehouseSendRelationRow['packages'];//件数
            if($tmpWarehouseSendRow['status'] == 3){
                $finishProductRow['number'] = $tmpWarehouseSendRelationRow['receive_number'];//数量
                $finishProductRow['packages'] = $tmpWarehouseSendRelationRow['receive_packages'];//件数
            }

            if(!$finishProductRow['packages']){
                $finishProductRow['packages'] = 0;
            }

            if($tmpWarehouseRow){
                $finishProductRow['warehouse_id'] = $tmpWarehouseRow['id'];//工单号
                $finishProductRow['order_title'] = $tmpWarehouseRow['order_title'];//工单号
                $finishProductRow['product_name'] = $tmpWarehouseRow['product_name'];//品名
                $finishProductRow['img_path'] = $tmpWarehouseRow['img_path'];//示例图
                $finishProductRow['order_type_title'] = $tmpWarehouseRow['order_type_title'];//工艺名称
                $finishProductRow['field_name_23'] = $tmpWarehouseRow['field_name_23'];//单位
                $finishProductRow['finished_specification'] = $tmpWarehouseRow['finished_specification'];//成品规格
                $finishProductRow['grammage'] = $tmpWarehouseRow['grammage'];//重量
                $finishProductRow['finished_date'] = $tmpWarehouseRow['finished_date'];//交货日期
            }else{
                $finishProductRow['warehouse_id'] = 0;
                $finishProductRow['order_title'] = '';
                $finishProductRow['product_name'] = '';
                $finishProductRow['img_path'] = '';
                $finishProductRow['order_type_title'] = '';
                $finishProductRow['field_name_23'] = '';
                $finishProductRow['finished_specification'] = '';
                $finishProductRow['grammage'] = '';
                $finishProductRow['finished_date'] = '';
            }

            $finishProductList[$tmpWarehouseBillId]['list'][] = $finishProductRow;
        }

        $finishProductList = array_values($finishProductList);

        //获取客户名称、电话、收货地址【取任一成品的信息】
        $addressAddress = '';
        if($tmpLogisticsNotesRow){
            $addressAddress = $tmpLogisticsNotesRow['province_name'].$tmpLogisticsNotesRow['city_name'].$tmpLogisticsNotesRow['area_name'].$tmpLogisticsNotesRow['address'];
        }

        $customerName = '';
        $customerTel = '';

        if($tmpWarehouseRow){
            $orderId = $tmpWarehouseRow['order_id'];
            $orderRow = \App\Eloquent\Ygt\Order::where(['id'=>$orderId])->first();
            if($orderRow){
                $customerId = $orderRow['customer_name'];
                $customerRow = \App\Eloquent\Ygt\Customer::where(['id'=>$customerId])->first();
                if($customerRow){
                    $customerName = $customerRow['customer_name'];
                    $customerTel = $customerRow['customer_tel'];
                }
            }
        }

        //能否修改数量，只有客户收货的时候允许修改数量
        $isEditNum = 0;
        if($tmpWarehouseSendRow['status'] == 2){
            if($isReplaceCustomer){//替客户收货
                $isEditNum = 1;
            }else{
                //如果是客户
                if($userId == $customerRow['user_id']){
                    $isEditNum = 1;
                }
            }
        }


        //发货单状态为1时，只有销售员显示确认发货按钮，其他人不显示按钮
        $buttonList = [];
        if($tmpWarehouseSendRow['status'] == 1){
            $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 13);
            if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
                $buttonList[] = [
                    'type' => '1',
                    'name' => '确认发货'
                ];
            }
        }

        //发货状态为2时，销售员显示代客户确认收货和直接确认收货，客户确认收货（销售代替收货后，页面同客户收货一致）
        if($tmpWarehouseSendRow['status'] == 2){
            $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 13);
            if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
                if($isReplaceCustomer){
                    $buttonList[] =
                        [
                            'type' => '4',
                            'name' => '确认收货'//客户确认收货
                        ];
                }else{
                    $buttonList[] = [
                        'type' => '2',
                        'name' => '代客确认收货'
                    ];
//                    $buttonList[] = [
//                        'type' => '3',
//                        'name' => '直接确认收货'//销售确认收货
//                    ];

                }
            }

            if($userInfo['privilege_id'] == 110){
                $buttonList[] =
                    [
                        'type' => '4',
                        'name' => '确认收货'//客户确认收货
                    ];
            }

        }

        if($tmpLogisticsNotesRow){
            $tmpLogisticsNotesRow['weight'] =\App\Engine\Common::weightDeal($tmpLogisticsNotesRow['weight']);//重量数据处理
        }

        if(!$tmpLogisticsNotesRow){//异常处理
            $tmpLogisticsNotesRow['logistics_sn'] = '';
            $tmpLogisticsNotesRow['number'] = 0;
            $tmpLogisticsNotesRow['packages'] = 0;
            $tmpLogisticsNotesRow['weight'] = 0;
            $tmpLogisticsNotesRow['freight'] = 0;
            $tmpLogisticsNotesRow['finish_time'] = '';
            $tmpLogisticsNotesRow['is_remind_finish'] = 0;
        }


        //返回数据
        $re = [];
        $re['logistics_line'] = $logisticsLine;//专线
        $re['logistics'] = $logistics;//物流公司
        $re['logistics_sn'] = $tmpLogisticsNotesRow['logistics_sn'];//运单号
        $re['driving_license_img'] = $drivingLicenseImg;//行驶证
        $re['driver_license_img'] = $driverLicenseImg;//驾驶证
        $re['other_img_list'] = $otherImgList;//附件图
        $re['send_time'] = $sendTime;//发货时间
        $re['number'] = $tmpLogisticsNotesRow['number'];//总数
        $re['packages'] = $tmpLogisticsNotesRow['packages'];//件数
        $re['weight'] = $tmpLogisticsNotesRow['weight'];//重量
        $re['freight'] = $tmpLogisticsNotesRow['freight'];//运费
        $re['finish_time'] = $tmpLogisticsNotesRow['finish_time'];//到货时间
        $re['is_remind_finish'] = $tmpLogisticsNotesRow['is_remind_finish'];//到货提醒
        $re['finish_product_list'] = $finishProductList;//成品信息
        $re['address_address'] = $addressAddress;//地址
        $re['customer_name'] = $customerName;//客户名称
        $re['customer_tel'] = $customerTel;//客户联系方式
        $re['is_edit_num'] = $isEditNum;//能否修改数量
        $re['button_list'] = $buttonList;//展示的按钮
        $re['page_title'] = '发货单详情';//详情页标题

        return $re;
    }

    //收货修改数量&扣金额
    public function warehouseSendReceive(){
        $warehouseSendId = request('warehouse_send_id');
        $isDirectReceive = request('is_direct_receive');

        //获取登陆用户信息
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        $tmpWarehouseSendRow = \App\Eloquent\Ygt\WarehouseSend::where(['id'=>$warehouseSendId])->first();
        $companyId = $tmpWarehouseSendRow['company_id'];

        if($tmpWarehouseSendRow['status'] == 3){
            return [
                'code' => 1,
                'message' => '已确认收货，请勿重复提交'
            ];
        }

//        $deductMoney = request('deduct_money');//扣款
//        $deductMoneyRegard = request('deduct_money_regard');//扣款理由

        $customerOrderId = 0;//获取个订单ID用于发送消息

        //收货数量
        $finishedProductList = [];
        $finishedProductListJson = request('finished_product_list');
        if($finishedProductListJson){
            $finishedProductList = json_decode(htmlspecialchars_decode($finishedProductListJson), true);
        }

        //直接收货
        if($isDirectReceive){
            //直接收货
            $tmpWarehouseSendRelationList = \App\Eloquent\Ygt\WarehouseSendRelation::where(['warehouse_send_id'=>$warehouseSendId])->get();
            foreach ($tmpWarehouseSendRelationList as $tmpWarehouseSendRelationRow){
                if($tmpWarehouseSendRelationRow){
                    $tmpWarehouseSendRelationRow->receive_number = $tmpWarehouseSendRelationRow->number;
                    $tmpWarehouseSendRelationRow->receive_packages = $tmpWarehouseSendRelationRow->packages;
                    $tmpWarehouseSendRelationRow->save();
                }
            }

        }else{
            //直接收货不会出现扣款
            //填写收货件数
            if(!empty($finishedProductList)){
                foreach ($finishedProductList as $tmpFinishedProductRow){
                    $tmpWarehouseId = $tmpFinishedProductRow['warehouse_id'];
                    $tmpWarehouseBillId = $tmpFinishedProductRow['warehouse_bill_id'];
                    $tmpNum = $tmpFinishedProductRow['num'];
                    $tmpPackages = $tmpFinishedProductRow['packages'];

                    $tmpWarehouseSendRelation = \App\Eloquent\Ygt\WarehouseSendRelation::where(['warehouse_send_id'=>$warehouseSendId,'warehouse_id'=>$tmpWarehouseId])->first();
                    if($tmpWarehouseSendRelation){
                        $tmpWarehouseSendRelation->receive_number = $tmpNum;
                        $tmpWarehouseSendRelation->receive_packages = $tmpPackages;
                        $tmpWarehouseSendRelation->save();

                        //应收单进行扣款 - 通过收货数量的差，修改应付单的金额
                        $tmpWarehouseBillMoneyRow =  \App\Eloquent\Ygt\WarehouseBillMoney::where(['warehouse_bill_id'=>$tmpWarehouseBillId])->first();
                        $tmpWarehouseBillRow = \App\Eloquent\Ygt\WarehouseBill::where(['id'=>$tmpWarehouseBillId])->first();
                        $tmpWarehouseBillRelation = \App\Eloquent\Ygt\WarehouseBillRelation::where(['warehouse_bill_id'=>$tmpWarehouseBillId,'warehouse_id'=>$tmpWarehouseId])->first();
                        $tmpPrice = $tmpWarehouseBillRelation['price'];

                        if($tmpWarehouseSendRelation->number - $tmpWarehouseSendRelation->receive_number){
                            $tmpWarehouseBillMoneyRow->deduct_money = ($tmpWarehouseSendRelation->number - $tmpWarehouseSendRelation->receive_number) * $tmpPrice;
                            $tmpWarehouseBillMoneyRow->deduct_money_regard = "未全部收货扣款";
                            $tmpWarehouseBillMoneyRow->save();
                        }

                    }
                }
            }
        }




        //修改应收单的金额&扣款&扣款理由
        //获取到对应的应收单
        $tmpWarehouseOutRelationIdArr = \App\Eloquent\Ygt\WarehouseSendRelation::where(['warehouse_send_id'=>$warehouseSendId])->get()->pluck('out_relation_id');
        $tmpWarehouseBillIdArr = \App\Eloquent\Ygt\WarehouseOutRelation::whereIn('id',$tmpWarehouseOutRelationIdArr)->get()->pluck('warehouse_bill_id');

        $tmpWarehouseBillMoneyList =  \App\Eloquent\Ygt\WarehouseBillMoney::whereIn('warehouse_bill_id',$tmpWarehouseBillIdArr)->get();
        foreach ($tmpWarehouseBillMoneyList as $tmpWarehouseBillMoneyRow){
            //获取个订单ID用于发送消息
            if(!$customerOrderId){
                $tmpWarehouseBillId = $tmpWarehouseBillMoneyRow['warehouse_bill_id'];//交货单ID
                $tmpWarehouseBillRelation = \App\Eloquent\Ygt\WarehouseBillRelation::where(['warehouse_bill_id'=>$tmpWarehouseBillId])->first();
                $tmpOrderId = $tmpWarehouseBillRelation['order_id'];
                $customerOrderId = \App\Eloquent\Ygt\Order::where(['id'=>$tmpOrderId])->first()->customer_order_id;
            }


//            if(!$isDirectReceive){
//                $tmpWarehouseSendRelationList = \App\Eloquent\Ygt\WarehouseSendRelation::where(['warehouse_send_id'=>$warehouseSendId])->get();
//                foreach ($tmpWarehouseSendRelationList as $tmpWarehouseSendRelationRow){
//                    if($tmpWarehouseSendRelationRow){
//                        $tmpWarehouseSendRelationRow->receive_number = $tmpWarehouseSendRelationRow->number;
//                        $tmpWarehouseSendRelationRow->receive_packages = $tmpWarehouseSendRelationRow->packages;
//                        $tmpWarehouseSendRelationRow->save();
//                    }
//                }
//            }


//            $tmpWarehouseBillMoneyRow->deduct_money = $deductMoney;
//            $tmpWarehouseBillMoneyRow->deduct_money_regard = $deductMoneyRegard;
//            $tmpWarehouseBillMoneyRow->save();
        }

        //修改交货单状态
        $tmpWarehouseBillList =  \App\Eloquent\Ygt\WarehouseBill::whereIn('id',$tmpWarehouseBillIdArr)->get();
        foreach ($tmpWarehouseBillList as $tmpWarehouseBillRow){
            $tmpWarehouseBillRow->status = 5;
            $tmpWarehouseBillRow->save();
        }

        //修改发货单状态
        $tmpWarehouseSendRow->status = 3;//已收货
        $tmpWarehouseSendRow->save();


        //发送消息给销售员和发货员
        //获取对应的订单ID
        $foreignKey = $customerOrderId;

        //给销售员
        $customerId = \App\Eloquent\Ygt\CustomerOrder::where(['id'=>$customerOrderId])->first()->customer_name;
        $customerRow = \App\Eloquent\Ygt\Customer::where(['id'=>$customerId])->first();
        $addUserId = 0;
        if($customerRow){
            $addUserId = $customerRow['add_user_id'];
        }

        if($addUserId){
            $data = [
                'company_id' => $companyId,
                'privilege_id' => '',
                'form_user_id' => $userId,
                'to_user_id' => $addUserId,
                'foreign_key' => $foreignKey,
                'type' => 43,//发货单详情
                'type_id' => $warehouseSendId,
                'title' => '订单已确认收货',
                'content' => '订单已确认收货',
                'theme' => '订单已确认收货',
            ];
            \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
        }

        //给发货员
        if($tmpWarehouseSendRow['user_id']){
            $data = [
                'company_id' => $companyId,
                'privilege_id' => '',
                'form_user_id' => $userId,
                'to_user_id' => $tmpWarehouseSendRow['user_id'],
                'foreign_key' => $foreignKey,
                'type' => 43,//发货单详情
                'type_id' => $warehouseSendId,
                'title' => '订单已确认收货',
                'content' => '订单已确认收货',
                'theme' => '订单已确认收货',
            ];
            \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
        }





        return '操作成功';
    }

    //客户核销-流水核销
    public function customerWriteOffWater(){
        $customerId = request('customer_id');
        $companyId = request('company_id');
        $writeOffMoney = request('write_off_money');//销账金额

        $title = request('title');//名称
        $billCategoryId     = request('bill_category_id',0);//分类
        $billAccountId      = request('bill_account_id',0);//账单
        $billAccountPayId      = request('bill_account_pay_id',0);//账单
        $billBuyerId        = request('bill_buyer_id',0);//往来单位
        $remark = request('remark');//备注
        $imgId = request('img_id');//附近图片

        //获取登陆用户信息
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        $isSeller = false;//收款方是否为销售员
        $customerRow = \App\Eloquent\Ygt\Customer::where(['id'=>$customerId])->first();
        $addUserId = $customerRow['add_user_id'];

        if($addUserId){
            //获取销售员信息
            $addUserInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($addUserId)->toArray();

            //获取账单信息
            $tmpBillAccountRow = \App\Eloquent\Ygt\BillAccount::where(['id'=>$billAccountId])->first();
            if($tmpBillAccountRow){
                if(strstr($tmpBillAccountRow['title'],$addUserInfo['truename'])){
                    $isSeller = true;
                }
            }
        }


        //获取客户的未销账账单
        $customerOrderId = 0;//获取个订单ID用于发送消息

        $where = [];
        $where[] = ['customer_id','=',$customerId];
        $where[] = ['company_id','=',$companyId];
        $where[] = ['now_money','>',0];
        $tmpWarehouseBillMoneyList = \App\Eloquent\Ygt\WarehouseBillMoney::where($where)->get();
        $writeOffWarehouseBillMoneyIdList = [];//被销账的账单ID
        foreach ($tmpWarehouseBillMoneyList as $tmpWarehouseBillMoneyRow){
            //获取个订单ID用于发送消息
            if(!$customerOrderId){
                $tmpWarehouseBillId = $tmpWarehouseBillMoneyRow['warehouse_bill_id'];//交货单ID
                $tmpWarehouseBillRelation = \App\Eloquent\Ygt\WarehouseBillRelation::where(['warehouse_bill_id'=>$tmpWarehouseBillId])->first();
                $tmpOrderId = $tmpWarehouseBillRelation['order_id'];
                $customerOrderId = \App\Eloquent\Ygt\Order::where(['id'=>$tmpOrderId])->first()->customer_order_id;
            }

            //过滤不需要核销的账单
            $needWriteOffMoney = $tmpWarehouseBillMoneyRow['pre_money'] - $tmpWarehouseBillMoneyRow['money'] - $tmpWarehouseBillMoneyRow['deduct_money'];
            if($needWriteOffMoney <= 0){
                continue;
            }


            if($needWriteOffMoney >=  $writeOffMoney){
                $writeOffWarehouseBillMoneyIdList[] = [
                    'id' => $tmpWarehouseBillMoneyRow['id'],
                    'money' => $writeOffMoney,
                ];
                $tmpWarehouseBillMoneyRow['now_money'] = $tmpWarehouseBillMoneyRow['now_money'] - $writeOffMoney;
                $tmpWarehouseBillMoneyRow['money'] = $tmpWarehouseBillMoneyRow['money'] + $writeOffMoney;

                if($isSeller){
                    $tmpWarehouseBillMoneyRow['status'] = 3;
                }else{
                    $tmpWarehouseBillMoneyRow['status'] = 2;
                }

                $tmpWarehouseBillMoneyRow->save();
                $writeOffMoney = 0;
                break;
            }else{
                $writeOffWarehouseBillMoneyIdList[] = [
                    'id' => $tmpWarehouseBillMoneyRow['id'],
                    'money' => $tmpWarehouseBillMoneyRow['now_money'],
                ];
                $tmpWarehouseBillMoneyRow['money'] = $tmpWarehouseBillMoneyRow['money'] + $needWriteOffMoney;
                $tmpWarehouseBillMoneyRow['now_money'] = 0;

                if($isSeller){
                    $tmpWarehouseBillMoneyRow['status'] = 3;
                }else{
                    $tmpWarehouseBillMoneyRow['status'] = 2;
                }

                $tmpWarehouseBillMoneyRow->save();
                $writeOffMoney -= $needWriteOffMoney;
            }
    }

        //保存销账记录
//        $billLogData = [
//            'title' => $title,
//            'bill_category_id' => $billCategoryId,
//            'bill_account_id' => $billAccountId,
//            'bill_buyer_id' => $billBuyerId,
//            'img_id' => $imgId,
//            'remark' => $remark,
//            'customer_id' => $customerId,
//        ];
//        $this->saveCustomerWriteOffWarehouseBillMoney($writeOffWarehouseBillMoneyIdList,$billLogData);

        if(!empty($writeOffWarehouseBillMoneyIdList)){
            $tmpObj = \App\Eloquent\Ygt\WriteOff::firstOrNew(['id'=>'']);
            $tmpObj->uid = $userId;
            $tmpObj->save();
            $tmpWriteOffId = $tmpObj->id;

            foreach ($writeOffWarehouseBillMoneyIdList as $writeOffWarehouseBillMoneyRow){
                $writeOffWarehouseBillMoneyId = $writeOffWarehouseBillMoneyRow['id'];
                $writeOffWarehouseBillMoneyMoney = $writeOffWarehouseBillMoneyRow['money'];
                $tmpObj = \App\Eloquent\Ygt\WriteOffDetail::firstOrNew(['id'=>'']);
                $tmpObj->write_off_id = $tmpWriteOffId;
                $tmpObj->warehouse_bill_money_id = $writeOffWarehouseBillMoneyId;
                $tmpObj->save();

                //添加销账流水记录
                $tmpObj = \App\Eloquent\Ygt\BillLog::firstOrNew(['id'=>'']);
                if(!$imgId){
                    $imgId = '';
                }
                $tmpInsertRow = [
                    'type' => 1,
                    'company_id' => $companyId,
                    'title' => '流水销账',
                    'bill_category_id' => $billCategoryId,
                    'bill_account_id' => $billAccountId,
                    'bill_buyer_id' => $billBuyerId,
                    'img_id' => $imgId,
                    'money' => $writeOffWarehouseBillMoneyMoney,
                    'remark' => $remark,
                    'table' => 'ygt_warehouse_bill_money',
                    'table_id' => $writeOffWarehouseBillMoneyId,
                    'customer_id' => $customerId,
                ];
                $tmpObj->fill($tmpInsertRow);
                $tmpObj->save();
            }

            //发送消息给销售和财务
            //获取对应的订单ID
            $foreignKey = $customerOrderId;

            //给财务
            $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 11);
            foreach ($privilegeIdList as $privilegeId) {
                if ($privilegeId) {
                    $data = [
                        'company_id' => $companyId,
                        'privilege_id' => $privilegeId,
                        'form_user_id' => $userId,
                        'to_user_id' => '',
                        'foreign_key' => $foreignKey,
                        'type' => 44,//type待定
                        'type_id' => $tmpWriteOffId,
                        'title' => '有新的核销单',
                        'content' => '有新的核销单',
                        'theme' => '有新的核销单',
                    ];
                    \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
                }
            }

            //给销售员
            if($addUserId){
                $data = [
                    'company_id' => $companyId,
                    'privilege_id' => '',
                    'form_user_id' => $userId,
                    'to_user_id' => $addUserId,
                    'foreign_key' => $foreignKey,
                    'type' => 44,//type待定
                    'type_id' => $tmpWriteOffId,
                    'title' => '有新的核销单',
                    'content' => '有新的核销单',
                    'theme' => '有新的核销单',
                ];
                \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
            }

        }



        return  '操作成功';
    }


    //客户核销-账单核销
    public function customerWriteOffBill(){
        $customerId = request('customer_id');
        $companyId = request('company_id');
//        $warehouseBillMoneyIdsStr = request('warehouse_bill_money_ids');//销账金额
        $warehouseBillMoneyListJson = request('warehouse_bill_money_list');//销账金额

        //处理传入json数据
        $warehouseBillMoneyList = json_decode(htmlspecialchars_decode($warehouseBillMoneyListJson), true);


        $title = request('title');//名称
        $billCategoryId     = request('bill_category_id',0);//分类
        $billAccountPayId      = request('bill_account_pay_id',0);//付款账单
        $billAccountId      = request('bill_account_id',0);//收款账单
        $billBuyerId        = request('bill_buyer_id',0);//往来单位
        $remark = request('remark');//备注
        $imgId = request('img_id');//附近图片

        //获取登陆用户信息
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();



        $isSeller = false;//收款方是否为销售员
        $customerRow = \App\Eloquent\Ygt\Customer::where(['id'=>$customerId])->first();
        $addUserId = $customerRow['add_user_id'];
        if($addUserId){
            //获取销售员信息
            $addUserInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($addUserId)->toArray();

            //获取账单信息
            $tmpBillAccountRow = \App\Eloquent\Ygt\BillAccount::where(['id'=>$billAccountId])->first();
            if($tmpBillAccountRow){
                if(strstr($tmpBillAccountRow['title'],$addUserInfo['truename'])){
                    $isSeller = true;
                }
            }
        }

//        $warehouseBillMoneyIdsArr = explode(',',$warehouseBillMoneyIdsStr);
//        //获取客户的未销账账单
//        $tmpWarehouseBillMoneyList = \App\Eloquent\Ygt\WarehouseBillMoney::whereIn('id',$warehouseBillMoneyIdsArr)->get();

        $writeOffWarehouseBillMoneyIdList = [];//被销账的账单ID
        $customerOrderId = 0;//获取个订单ID用于发送消息

        foreach ($warehouseBillMoneyList as $warehouseBillMoneyRow){
            //获取对应的应收单
            $tmpWarehouseBillMoneyRow = \App\Eloquent\Ygt\WarehouseBillMoney::where(['id'=>$warehouseBillMoneyRow['warehouse_bill_money_id']])->first();

            //获取个订单ID用于发送消息
            if(!$customerOrderId){
                $tmpWarehouseBillId = $tmpWarehouseBillMoneyRow['warehouse_bill_id'];//交货单ID
                $tmpWarehouseBillRelation = \App\Eloquent\Ygt\WarehouseBillRelation::where(['warehouse_bill_id'=>$tmpWarehouseBillId])->first();
                $tmpOrderId = $tmpWarehouseBillRelation['order_id'];
                $customerOrderId = \App\Eloquent\Ygt\Order::where(['id'=>$tmpOrderId])->first()->customer_order_id;
            }

            if($tmpWarehouseBillMoneyRow){
                $writeOffWarehouseBillMoneyIdList[] = [
                    'id' => $warehouseBillMoneyRow['warehouse_bill_money_id'],
                    'money' => $warehouseBillMoneyRow['write_off_money'],
                ];

                $tmpWarehouseBillMoneyRow['money'] = $tmpWarehouseBillMoneyRow['money'] + $warehouseBillMoneyRow['write_off_money'];
                $tmpWarehouseBillMoneyRow['now_money'] = $tmpWarehouseBillMoneyRow['now_money'] - $warehouseBillMoneyRow['write_off_money'];

                if($isSeller){
                    $tmpWarehouseBillMoneyRow['status'] = 3;
                }else{
                    $tmpWarehouseBillMoneyRow['status'] = 2;
                }

                $tmpWarehouseBillMoneyRow->save();
            }
        }

        //保存销账记录
        if(!empty($writeOffWarehouseBillMoneyIdList)){
            $tmpObj = \App\Eloquent\Ygt\WriteOff::firstOrNew(['id'=>'']);
            $tmpObj->uid = $userId;
            $tmpObj->status = 1;
            $tmpObj->save();
            $tmpWriteOffId = $tmpObj->id;

            foreach ($writeOffWarehouseBillMoneyIdList as $writeOffWarehouseBillMoneyRow){
                $writeOffWarehouseBillMoneyId = $writeOffWarehouseBillMoneyRow['id'];
                $writeOffWarehouseBillMoneyMoney = $writeOffWarehouseBillMoneyRow['money'];
                $tmpObj = \App\Eloquent\Ygt\WriteOffDetail::firstOrNew(['id'=>'']);
                $tmpObj->write_off_id = $tmpWriteOffId;
                $tmpObj->warehouse_bill_money_id = $writeOffWarehouseBillMoneyId;
                $tmpObj->save();

                //添加销账流水记录
                $tmpObj = \App\Eloquent\Ygt\BillLog::firstOrNew(['id'=>'']);
                if(!$imgId){
                    $imgId = '';
                }

                $tmpInsertRow = [
                    'type' => 1,
                    'company_id' => $companyId,
                    'title' => '账单销账',
                    'bill_category_id' => $billCategoryId,
                    'bill_account_pay_id' => $billAccountPayId,
                    'bill_account_id' => $billAccountId,
                    'bill_buyer_id' => $billBuyerId,
                    'img_id' => $imgId,
                    'money' => $writeOffWarehouseBillMoneyMoney,
                    'remark' => $remark,
                    'table' => 'ygt_warehouse_bill_money',
                    'table_id' => $writeOffWarehouseBillMoneyId,
                    'customer_id' => $customerId,
                ];
                $tmpObj->fill($tmpInsertRow);
                $tmpObj->save();
            }
        }



        //发送消息给销售和财务
        //获取对应的订单ID
        $foreignKey = $customerOrderId;

        //给财务
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 11);
        foreach ($privilegeIdList as $privilegeId) {
            if ($privilegeId) {
                $data = [
                    'company_id' => $companyId,
                    'privilege_id' => $privilegeId,
                    'form_user_id' => $userId,
                    'to_user_id' => '',
                    'foreign_key' => $foreignKey,
                    'type' => 44,//type待定
                    'type_id' => $tmpWriteOffId,
                    'title' => '有新的核销单',
                    'content' => '有新的核销单',
                    'theme' => '有新的核销单',
                ];
                \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
            }
        }

        //给销售员
        if($addUserId){
            $data = [
                'company_id' => $companyId,
                'privilege_id' => '',
                'form_user_id' => $userId,
                'to_user_id' => $addUserId,
                'foreign_key' => $foreignKey,
                'type' => 44,//type待定
                'type_id' => $tmpWriteOffId,
                'title' => '有新的核销单',
                'content' => '有新的核销单',
                'theme' => '有新的核销单',
            ];
            \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
        }

        return  '操作成功';
    }


    //财务(销售)销账
    public function financeWriteOff(){
        $writeOffId = request('write_off_id');
        $writeOffType = request('write_off_type');//1-未收款销账 2-收款销账 100-销售确认转账
        if(!$writeOffType){
            $writeOffType = request('type');//1-未收款销账 2-收款销账 100-销售确认转账
        }

        //获取登陆用户信息
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();

        $warehouseBillMoneyIdArr = \App\Eloquent\Ygt\WriteOffDetail::where(['write_off_id'=>$writeOffId])->get()->pluck('warehouse_bill_money_id');
        $warehouseBillMoneyList = \App\Eloquent\Ygt\WarehouseBillMoney::whereIn('id',$warehouseBillMoneyIdArr)->get();

        $customerOrderId = 0;//获取个订单ID用于发送消息
        foreach ($warehouseBillMoneyList as $warehouseBillMoneyRow){
            $companyId = $warehouseBillMoneyRow['company_id'];

            //获取个订单ID用于发送消息
            if(!$customerOrderId){
                $tmpWarehouseBillId = $warehouseBillMoneyRow['warehouse_bill_id'];//交货单ID
                $tmpWarehouseBillRelation = \App\Eloquent\Ygt\WarehouseBillRelation::where(['warehouse_bill_id'=>$tmpWarehouseBillId])->first();
                $tmpOrderId = $tmpWarehouseBillRelation['order_id'];
                $customerOrderId = \App\Eloquent\Ygt\Order::where(['id'=>$tmpOrderId])->first()->customer_order_id;
            }


            $warehouseBillMoneyRow->receive_money = $warehouseBillMoneyRow['money'];
            if($writeOffType == 1){
                $warehouseBillMoneyRow['status'] = 4;
            }
            if($writeOffType == 2){
                $warehouseBillMoneyRow['status'] = 5;
            }
            if($writeOffType == 100){
                $warehouseBillMoneyRow['status'] = 100;
            }

            $warehouseBillMoneyRow->save();
        }


        $foreignKey = $customerOrderId;

        $customerUid = '';
        $customerId = \App\Eloquent\Ygt\CustomerOrder::where(['id'=>$customerOrderId])->first()->customer_name;
        $customerRow = \App\Eloquent\Ygt\Customer::where(['id'=>$customerId])->first();

        if($customerRow){
            $addUserId = $customerRow['add_user_id'];
        }

        //未收款销账 - 给客户和销售发消息
        if($writeOffType == 1){
            //修改核销单状态
            $tmpWriteOffRow = \App\Eloquent\Ygt\WriteOff::where(['id'=>$writeOffId])->first();
            $tmpWriteOffRow->status = 2;
            $tmpWriteOffRow->save();

            //给客户发消息
            if($customerRow){
                $customerUid = $customerRow['user_id'];
                $data = [
                    'company_id' => 2,
                    'privilege_id' => '',
                    'form_user_id' => $userId,
                    'to_user_id' => $customerUid,
                    'foreign_key' => $foreignKey,
                    'type' => 44,//账单详情
                    'type_id' => $writeOffId,
                    'title' => '账单已核销',
                    'content' => '账单已核销',
                    'theme' => '账单已核销',
                ];
                \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
            }


            //给销售发消息
            if($addUserId){
                $data = [
                    'company_id' => $companyId,
                    'privilege_id' => '',
                    'form_user_id' => $userId,
                    'to_user_id' => $addUserId,
                    'foreign_key' => $foreignKey,
                    'type' => 44,//账单详情
                    'type_id' => $writeOffId,
                    'title' => '账单未收款核销',
                    'content' => '账单未收款核销',
                    'theme' => '账单未收款核销',
                ];
                \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
            }



        }

        //收款销账 - 给销售发消息
        if($writeOffType == 2){
            //修改核销单状态
            $tmpWriteOffRow = \App\Eloquent\Ygt\WriteOff::where(['id'=>$writeOffId])->first();
            $oldStatus = $tmpWriteOffRow->status;
            $tmpWriteOffRow->status = 3;
            $tmpWriteOffRow->save();

            //直接收款核销才需要给客户发消息
            if($oldStatus == 1){
                if($customerRow){
                    $customerUid = $customerRow['user_id'];
                    $data = [
                        'company_id' => 2,
                        'privilege_id' => '',
                        'form_user_id' => $userId,
                        'to_user_id' => $customerUid,
                        'foreign_key' => $foreignKey,
                        'type' => 44,//账单详情
                        'type_id' => $writeOffId,
                        'title' => '账单已核销',
                        'content' => '账单已核销',
                        'theme' => '账单已核销',
                    ];
                    \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
                }
            }

            //给销售发消息
            if($addUserId){
                $data = [
                    'company_id' => $companyId,
                    'privilege_id' => '',
                    'form_user_id' => $userId,
                    'to_user_id' => $addUserId,
                    'foreign_key' => $foreignKey,
                    'type' => 44,//账单详情
                    'type_id' => $writeOffId,
                    'title' => '账单收款核销',
                    'content' => '账单收款核销',
                    'theme' => '账单收款核销',
                ];
                \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
            }
        }

        //100-销售确认转账 - 给财务发消息
        if($writeOffType == 100){
            //修改核销单状态
            $tmpWriteOffRow = \App\Eloquent\Ygt\WriteOff::where(['id'=>$writeOffId])->first();
            $oldStatus = $tmpWriteOffRow->status;
            $tmpWriteOffRow->status = 100;
            $tmpWriteOffRow->save();

            //给财务发消息
            //给财务
            $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 11);
            foreach ($privilegeIdList as $privilegeId) {
                if ($privilegeId) {
                    $data = [
                        'company_id' => $companyId,
                        'privilege_id' => $privilegeId,
                        'form_user_id' => $userId,
                        'to_user_id' => '',
                        'foreign_key' => $foreignKey,
                        'type' => 44,//账单详情
                        'type_id' => $writeOffId,
                        'title' => '销售已转账',
                        'content' => '销售已转账',
                        'theme' => '销售已转账',
                    ];
                    \App\Eloquent\Ygt\UserMessage::sendCustomerOrderMessage($data);
                }
            }


        }




        return  '操作成功';
    }

    //核销单详情
    public function getWriteOffDetail(){
        $writeOffId = request('write_off_id');

        //获取登陆用户信息
        $userId = \App\Engine\Func::getHeaderValueByName('userid');
        $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($userId)->toArray();
        $companyId = $userInfo['company_id'];

        $warehouseBillMoneyIdArr = \App\Eloquent\Ygt\WriteOffDetail::where(['write_off_id'=>$writeOffId])->get()->pluck('warehouse_bill_money_id');

        //数据和账单列表一致
        $where = [];
        $collection         = \App\Eloquent\Ygt\WarehouseBillMoney::whereIn('id',$warehouseBillMoneyIdArr)->get();
        $lists              = $collection->toArray();
        $totalMoeny         = 0;
        foreach ($lists as $key=>$val)
        {
            $totalMoeny     += $val['money'];

            if(!$val['deduct_money']){
                $lists[$key]['deduct_money'] = 0;
            }

            $valCreatedAt   = $val['created_at'];
            $lists[$key]['created_at']  = date('Y-m-d',$valCreatedAt);

            $where          = ['warehouse_bill_id'=>$val['warehouse_bill_id']];
            $relationObj    = \App\Eloquent\Ygt\WarehouseBillRelation::getList($where);
            $warehouseIdArr = $relationObj->pluck('warehouse_id');
            $where          = ['id'=>['in',$warehouseIdArr]];
            $orderList      = \App\Eloquent\Ygt\Warehouse::getList($where)->toArray();
            $imgPathArr     = [];
            foreach($orderList as $k=>$v)
            {
                if(!empty($v['img_path']))
                {
                    $imgPathArr[]   = $v['img_path'];
                }
            }
            $lists[$key]['img_path_arr'] = $imgPathArr;
            $lists[$key]['money'] = '已收金额: '.$val['money'];
            $lists[$key]['pre_money'] = '应收金额: '.$val['pre_money'];

            $status = $lists[$key]['status'];
            //状态兼容
            if($status == 1){
                $lists[$key]['status'] = 0;
            }
            //如果状态4、5，且收款已収齐
            if(in_array($status,[4,5])){
                if($val['deduct_money'] + $val['money'] == $val['pre_money']){
                    $lists[$key]['status'] = 1;
                }
            }

        }

        $totalMoeny = sprintf('%.2f',$totalMoeny );
        $result             = ['bill_list'=>$lists,'total_money'=>$totalMoeny];

        //财务权限的账号有按钮
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 11);
        if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
            $tmpWriteOffRow = \App\Eloquent\Ygt\WriteOff::where(['id'=>$writeOffId])->first();
            if($tmpWriteOffRow['status'] == 1){
                $result['button_list'] = [
                    [
                        'title' => '未收账核销',
                        'type' => '1',
                    ],
                    [
                        'title' => '收账核销',
                        'type' => '2',
                    ],
                ];
            }
            if($tmpWriteOffRow['status'] == 100){
                $result['button_list'] = [
                    [
                        'title' => '确认收账',
                        'type' => '2',
                    ],
                ];
            }
        }

        //财务未收款销账时，销售需要按钮
        $privilegeIdList = \App\Engine\OrderEngine::getPrivilegeByNode($companyId, 13);
        if (in_array($userInfo['privilege_id'], $privilegeIdList)) {
            $tmpWriteOffRow = \App\Eloquent\Ygt\WriteOff::where(['id'=>$writeOffId])->first();
            if($tmpWriteOffRow['status'] == 2){
                $result['button_list'] = [
                    [
                        'title' => '确认收账',
                        'type' => '100',
                    ],
                ];
            }
        }






        return $result;

    }

}